//
//  CartoonCollectDatabase.m
//  Double
//
//  Created by dllo on 15/5/28.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "CartoonCollectDatabase.h"
#import <sqlite3.h>
#import "CartoonCollectModel.h"
#import "DB.h"
@implementation CartoonCollectDatabase
+ (void)commitSql:(NSString *)str
{
    sqlite3 * db = [DB openDB];
    int result = sqlite3_exec(db, [str UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"数据库开启成功");
    } else {
        NSLog(@"数据库开启失败");
    }
}

// 插入
+ (void)insertWithModel:(CartoonCollectModel *)model
{
    NSString * str = [NSString stringWithFormat:@"insert into CartoonCollect(Id, Name) values (%ld, '%@')", model.CartoonId, model.CartoonName];
    [CartoonCollectDatabase commitSql:str];
    NSLog(@"插入成功");
}
// 删除
+ (void)deleteWithModel:(CartoonCollectModel *)model
{
    NSString * str = [NSString stringWithFormat:@"delete from CartoonCollect where Id = %ld", model.CartoonId];
    [CartoonCollectDatabase commitSql:str];
}
// 更新
+ (void)updataWithModel:(NSInteger)Id Name:(NSString *)Name;
{
    NSString * str = [NSString stringWithFormat:@"updata CartoonCollect set Id = %ld, Name = '%@'", Id, Name];
    [CartoonCollectDatabase commitSql:str];
}
+ (NSArray *)selectAll
{
    NSString * str = @"select Id, Name from CartoonCollect";
    sqlite3 * db = [DB openDB];
    // 定义执行结果接收者 + 限制长度 -1 不限长度 &stmt查询结果所在位置
    sqlite3_stmt * stmt = nil;
    int result = sqlite3_prepare_v2(db, [str UTF8String], -1, &stmt, nil);
    NSMutableArray * array = [NSMutableArray array];
    if (result == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            int Id = sqlite3_column_int(stmt, 0);
            const unsigned char * Name = sqlite3_column_text(stmt, 1);
            // 把C语言字符串转换成oc字符串
            NSString * CartoonName = [NSString stringWithUTF8String:(const char *)Name];
            CartoonCollectModel * model = [CartoonCollectModel CartoonCollectModelWithCartoonId:Id CartoonName:CartoonName];
            [array addObject:model];
        }
    }
    return array;
}

@end
